package nancal.mp.db.mongo.extend


import nancal.mp.db.mongo.mor
import nancal.mp.db.mongo.table.AdminGroup
import nbcp.base.comm.ApiResult
import nbcp.base.db.LoginUserModel
import nbcp.base.extend.AsString
import nbcp.base.extend.minus
import nbcp.base.utils.Md5Util
import nbcp.base.utils.TokenUtil
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.update
import java.time.LocalDateTime


/**
 * 登录验证，返回错误消息
 */

fun AdminGroup.AdminUserEntity.doLogin(
    loginName: String,
    password: String,
    requestToken: String,
): ApiResult<LoginUserModel> {

    var loginUser = mor.admin.adminLoginUser.query()
        .where { it.loginName mongoEquals loginName }
        .toEntity();

    if (loginUser == null) {
        return ApiResult.error("找不到用户：" + loginName);
    }

    if (loginUser.errorLoginTimes > 10 && (LocalDateTime.now() - loginUser.lastLoginAt).seconds < 5) {
        return ApiResult.error("帐户频繁登录失败，已被锁定5分钟！")
    }

    var user = mor.admin.adminUser.query()
        .where { it.loginName mongoEquals loginName }
        .toEntity()

    if (user == null) {
        return ApiResult.error("找不到用户：" + loginName)
    }


    if (loginUser.password != Md5Util.getBase64Md5(password)) {

        mor.admin.adminLoginUser.update()
            .set { it.lastLoginAt to LocalDateTime.now() }
            .set { it.errorLoginTimes to (loginUser.errorLoginTimes + 1) }
            .where { it.loginName mongoEquals loginName }
            .exec();
        return ApiResult.error("密码错误")
    }

    var token = requestToken.AsString(TokenUtil.generateToken())
//    mor.admin.adminLoginUser.update()
//        .set { it.lastLoginAt to LocalDateTime.now() }
//        .set { it.errorLoginTimes to 0 }
//        .set { it.token to token }
//        .where { it.loginName mongoEquals loginName }
//        .exec();


    return ApiResult.of(
        LoginUserModel().apply {
            this.id = user.id
            this.loginName = user.loginName
            this.isAdmin = user.isAdmin
            this.name = user.name
            this.token = token
            this.system = "admin"
            this.loginField = "loginName"
            this.roles = user.roles.map { it.id }
        }
    );
}
